package com.mjk.common.tools.monitor.impl;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.NacosNamingService;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.tools.monitor.IMonitor;
import com.mjk.common.tools.springextend.BeeApplicationListener;
import com.mjk.common.tools.springextend.BeeSpringBean;
import com.mjk.common.util.ComputerUtils;
import com.mjk.common.util.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;

import java.io.File;
import java.util.*;

/**
 * 基于nacos的服务监控
 */
public class NacosMonitor implements IMonitor, BeeApplicationListener {
    /**
     * 节点端口
     */
    @Value(value = "${server.port:8080}")
    private int nodePort;
    /**
     * 服务监控名称
     */
    @Value(value = "${bee.nacos.service-name:manager}")
    private String serverName;
    /**
     * 服务监控名称
     */
    @Value(value = "${spring.application.name:manager}")
    private String projectName;
    /**
     * nacos服务中心
     */
    @Value(value = "${spring.cloud.nacos.discovery.server_addr:127.0.0.1:8849}")
    private String nacosAddress;

    @Override
    public List<ComputerUtils.ComputerInfo> getServices(String name) {
        try {
            NacosDiscoveryProperties nacosDiscoveryProperties = BeeSpringBean.getBean(NacosDiscoveryProperties.class);
            NacosNamingService nacosNamingService = new NacosNamingService(nacosDiscoveryProperties.getNacosProperties());
            List<Instance> instances;
            if (ObjectUtils.isEmpty(name)) {
                instances = nacosNamingService.getAllInstances(serverName);

            } else {
                instances = nacosNamingService.getAllInstances(name);
            }
            List<ComputerUtils.ComputerInfo> computerInfos = new ArrayList<>();
            instances.forEach(instance -> {
                ComputerUtils.ComputerInfo computerInfo = ComputerUtils.getComputerInfo();//获取本机信息
                computerInfo.setServiceName(instance.getServiceName().substring(instance.getServiceName().lastIndexOf("@") + 1));
                computerInfo.setPort(instance.getPort() + "");
                computerInfo.setIp(instance.getIp());
                computerInfo.setMateInfo(instance.getMetadata());
                computerInfo.setShowName(instance.getIp() + ":" + instance.getPort());
                computerInfos.add(computerInfo);
            });
            return computerInfos;
        } catch (Exception e) {
            return Collections.emptyList();
        }
    }


    @Override
    public void doApplicationContext(ApplicationContext applicationContext) {
        try {
            // 创建NamingService实例
            NamingService namingService = NacosFactory.createNamingService(nacosAddress);
            // 创建Instance实例，填入服务的IP、端口等信息
            Instance instance = new Instance();
            instance.setIp(ComputerUtils.getIpAddress()); // 实例IP
            instance.setPort(nodePort); // 实例端口
            // 添加自定义元数据
            Map<String, String> metadata = new HashMap<>();
            //服务存储路径
            File currentDirectory = new File("").getAbsoluteFile();
            metadata.put("path", currentDirectory.getParent());
            //系统信息
            metadata.put("os", System.getProperty("os.name"));
            instance.setMetadata(metadata);
            // 注册服务
            namingService.registerInstance(serverName, instance);
        } catch (Exception e) {
            BizLogger.error(e);
        }

    }
}
